package com.hectopascal.auth.component;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hectopascal.auth.bean.AdminUserDetails;
import com.hectopascal.exception.ServiceException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.MacAlgorithm;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "iat";
    @Resource
    private JwtConfig jwtConfig;

    private SecretKey secretKey;

    private static final MacAlgorithm hs512 = Jwts.SIG.HS512;
    @Value("${nologin.salt:anyald123}")
    private String salt;
    @PostConstruct
    public void init()
    {
        secretKey = Keys.hmacShaKeyFor(jwtConfig.getSecret().getBytes());
    }

    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .header()
                .add("type", "jwt")
                .add("alg", "HS512")
                .and()
                .claims(claims)
                .id(IdWorker.get32UUID())
                .expiration(generateExpirationDate())
                .issuedAt(new Date())
                .issuer("syxt")
                .signWith(secretKey, hs512)
                .compact();
    }

    //根据token返回Jws对象
    private Jws<Claims> parseClaims(String token) {
        return Jwts.parser()
                .verifyWith(secretKey)
                .build()
                .parseSignedClaims(token);
    }

    //根据token返回头部消息
    private JwsHeader parseHeader(String token) {
        return parseClaims(token).getHeader();
    }

    //根据token返回荷载消息
    private Claims parsePayload(String token) {
        return parseClaims(token).getPayload();
    }

    // 生成过期时间
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + jwtConfig.getExpiration() * 1000);
    }

    // 根据token返回用户名
    public String getUserNameFromToken(String token) {
        String username;
        try{
            Claims claims = parsePayload(token);
            username = claims.get(CLAIM_KEY_USERNAME, String.class);
        }catch (Exception e){
            username = null;
        }
        return username;
    }

    //为token生成Redis存储的key
    public String getRedisKey(String token) {
        if(StrUtil.isBlank(token)){
            throw new ServiceException("转化出错。");
        }
        return(":" + DigestUtil.md5Hex16(token));
    }

    //验证token是否有效
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    //验证token是否过期
    private boolean isTokenExpired(String token) {
        return getExpirationDateFromToken(token).before(new Date());
    }

    //根据token获取过期时间
    public Date getExpirationDateFromToken(String token) {
        return parsePayload(token).getExpiration();
    }

    //根据用户信息生成token
    public String generateToken(AdminUserDetails userDetails) {
        return generateToken(userDetails.getUsername());
    }

    //根据用户名生成token
    public String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, username);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    //判断token是否可以被刷新
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }

    //刷新token
    public String refreshToken(String token) {
        Claims claims = parsePayload(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    //对用户名进行签名处理
    public String signUsername(String username) {
        String md5Str = SecureUtil.md5( username+ salt).substring(0, 10);
        String baseStr = username + "|" + md5Str;
        return java.util.Base64.getEncoder().encodeToString(baseStr.getBytes(StandardCharsets.UTF_8));
    }
}
